import 'package:environmental_les_app/common/style/colours.dart';
import 'package:environmental_les_app/common/widgets/button_public_rect.dart';
import 'package:flutter/material.dart';

import 'bottom_pop_window_bg.dart';
import 'date_time_picker.dart';

class BottomScreenTimeDialog extends StatefulWidget {
  /// initialTimes 格式示例：{ 'alarm': { 'start': '2025-01-01 00:00:00', 'end': '2025-01-02 00:00:00' }, 'handle': { ... } }
  const BottomScreenTimeDialog({super.key, this.initialTimes});

  final Map<String, dynamic>? initialTimes;

  @override
  State<BottomScreenTimeDialog> createState() => _BottomScreenTimeDialogState();
}

class _BottomScreenTimeDialogState extends State<BottomScreenTimeDialog> {
  // 0 -> 报警时间, 1 -> 处理时间
  int _currentTab = 0;

  // 每个 tab 的开始和结束时间
  final List<DateTime?> _startTimes = [null, null];
  final List<DateTime?> _endTimes = [null, null];

  // 保存初始传入值，用于重置到初始状态
  final List<DateTime?> _initialStartTimes = [null, null];
  final List<DateTime?> _initialEndTimes = [null, null];

  @override
  void initState() {
    super.initState();
    // 从 widget.initialTimes 回写到内部状态
    final init = widget.initialTimes ?? {};
    void trySet(int idx, String key) {
      final map = init[key];
      if (map is Map) {
        DateTime? ps, pe;
        if (map['start'] is String) {
          ps = DateTime.tryParse(map['start']);
          ps ??= DateTime.tryParse('${map['start']}:00');
        }
        if (map['end'] is String) {
          pe = DateTime.tryParse(map['end']);
          pe ??= DateTime.tryParse('${map['end']}:00');
        }
        _startTimes[idx] = ps;
        _endTimes[idx] = pe;
        _initialStartTimes[idx] = ps;
        _initialEndTimes[idx] = pe;
      }
    }

    trySet(0, 'alarm');
    trySet(1, 'handle');
  }

  @override
  Widget build(BuildContext context) {
    return BottomPopWindowBg(
      title: "时间筛选",
      children: [
        // tabs
        Container(
          padding: const EdgeInsets.all(6),
          decoration: BoxDecoration(
            color: Colours.bgF2F3F5,
            borderRadius: BorderRadius.circular(6),
          ),
          child: Row(
            children: [
              _buildTab(0, '报警时间'),
              const SizedBox(width: 8),
              _buildTab(1, '处理时间'),
            ],
          ),
        ),

        const SizedBox(height: 18),

        // 开始时间
        const Align(
          alignment: Alignment.centerLeft,
          child: Text('开始时间',
              style: TextStyle(
                  fontSize: 16,
                  color: Colours.text254,
                  fontWeight: FontWeight.w500)),
        ),
        const SizedBox(height: 8),
        GestureDetector(
          onTap: () => _onPickDateTime(isStart: true),
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
            decoration: BoxDecoration(
              color: _startTimes[_currentTab] == null
                  ? Colours.bgF7F8FA
                  : Colours.bgECF5FF,
              borderRadius: BorderRadius.circular(6),
              border: Border.all(
                color: _startTimes[_currentTab] == null
                    ? Colors.transparent
                    : Colours.appMain,
                width: 1,
              ),
            ),
            child: Row(
              children: [
                Text(
                  _startTimes[_currentTab] == null
                      ? '选择时间'
                      : _format(_startTimes[_currentTab]!),
                  style: TextStyle(
                      fontSize: 14,
                      fontWeight: _startTimes[_currentTab] == null
                          ? FontWeight.w400
                          : FontWeight.w600,
                      color: _startTimes[_currentTab] == null
                          ? Colours.textC9CDD4
                          : Colours.appMain),
                ),
              ],
            ),
          ),
        ),

        const SizedBox(height: 18),

        // 结束时间
        const Align(
          alignment: Alignment.centerLeft,
          child: Text('结束时间',
              style: TextStyle(
                  fontSize: 16,
                  color: Colours.text254,
                  fontWeight: FontWeight.w500)),
        ),
        const SizedBox(height: 8),
        GestureDetector(
          onTap: () => _onPickDateTime(isStart: false),
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
            decoration: BoxDecoration(
              color: _endTimes[_currentTab] == null
                  ? Colours.bgF7F8FA
                  : Colours.bgECF5FF,
              borderRadius: BorderRadius.circular(6),
              border: Border.all(
                color: _endTimes[_currentTab] == null
                    ? Colors.transparent
                    : Colours.appMain,
                width: 1,
              ),
            ),
            child: Row(
              children: [
                Text(
                  _endTimes[_currentTab] == null
                      ? '选择时间'
                      : _format(_endTimes[_currentTab]!),
                  style: TextStyle(
                      fontSize: 14,
                      fontWeight: _endTimes[_currentTab] == null
                          ? FontWeight.w400
                          : FontWeight.w600,
                      color: _endTimes[_currentTab] == null
                          ? Colours.textC9CDD4
                          : Colours.appMain),
                ),
              ],
            ),
          ),
        ),

        const SizedBox(height: 22),

        // actions
        Row(
          children: [
            Expanded(
              flex: 1,
              child: ButtonPublicRect(
                text: "重置",
                type: ButtonPublicType.outline,
                onPressed: _onReset,
              ),
            ),
            const SizedBox(width: 12),
            Expanded(
              flex: 3,
              child: ButtonPublicRect(
                minWidth: double.infinity,
                text: "确认",
                onPressed: _onConfirm,
              ),
            ),
          ],
        ),
        const SizedBox(height: 6),
      ],
    );
  }

  Widget _buildTab(int idx, String label) {
    final selected = _currentTab == idx;
    return Expanded(
      child: GestureDetector(
        onTap: () {
          setState(() {
            _currentTab = idx;
          });
        },
        child: Container(
          padding: const EdgeInsets.symmetric(vertical: 6),
          decoration: BoxDecoration(
            color: selected ? Colors.white : Colors.transparent,
            borderRadius: BorderRadius.circular(6),
          ),
          alignment: Alignment.center,
          child: Text(label,
              style: TextStyle(
                  fontSize: 13,
                  fontWeight: selected ? FontWeight.w500 : FontWeight.w400,
                  color: selected ? Colours.textC4C : Colours.text254)),
        ),
      ),
    );
  }

  Future<void> _onPickDateTime({required bool isStart}) async {
    final now = DateTime.now();
    final initial = isStart
        ? (_startTimes[_currentTab] ?? now)
        : (_endTimes[_currentTab] ?? now);

    showDateTimePicker(
      initialDateTime: initial,
      dateFormat: "yyyy-MM-dd HH:mm",
      onCallback: (String? time) {
        if (!mounted) return;
        if (time == null) {
          return;
        }

        // 尝试解析字符串，若无秒则补 ":00"
        DateTime? parsed = DateTime.tryParse(time);
        parsed ??= DateTime.tryParse('$time:00');

        setState(() {
          if (parsed != null) {
            if (isStart) {
              _startTimes[_currentTab] = parsed;
            } else {
              _endTimes[_currentTab] = parsed;
            }
          }
        });
      },
    );
  }

  void _onReset() {
    setState(() {
      // 重置到初始传入值（如果有），否则清空
      _startTimes[_currentTab] = _initialStartTimes[_currentTab];
      _endTimes[_currentTab] = _initialEndTimes[_currentTab];
    });
  }

  void _onConfirm() {
    // 返回完整的时间筛选结果，包含 alarm 和 handle 两类（若为空则不包含该键）
    final Map<String, dynamic> result = {};
    if (_startTimes[0] != null || _endTimes[0] != null) {
      result['alarm'] = {
        'start': _startTimes[0] != null ? _format(_startTimes[0]!) : null,
        'end': _endTimes[0] != null ? _format(_endTimes[0]!) : null,
      };
    }
    if (_startTimes[1] != null || _endTimes[1] != null) {
      result['handle'] = {
        'start': _startTimes[1] != null ? _format(_startTimes[1]!) : null,
        'end': _endTimes[1] != null ? _format(_endTimes[1]!) : null,
      };
    }
    Navigator.of(context).pop(result.isEmpty ? {} : result);
  }

  String _format(DateTime dt) {
    String two(int v) => v < 10 ? '0$v' : '$v';
    return '${dt.year}-${two(dt.month)}-${two(dt.day)} ${two(dt.hour)}:${two(dt.minute)}:${two(dt.second)}';
  }
}
